package P05多线程锁.P02_FairLockAndNonFairLock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 非公平锁
 */
public class NonFairLock {
    public static void main(String[] args) {
        NonFairLockLTicket lTicket = new NonFairLockLTicket();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                lTicket.sell();
            }
        }, "aa").start();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                lTicket.sell();
            }
        }, "bb").start();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                lTicket.sell();
            }
        }, "cc").start();

    }
}

class NonFairLockLTicket {
    private Integer number = 30;

    private final ReentrantLock lock = new ReentrantLock();
    public void sell() {
        // 上锁
        lock.lock();
        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出：" + (number--) + " 剩下：" + number);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 解锁
            lock.unlock();
        }
    }
}
